import {
  login,
  logout,
  userInfo
} from '@/api/system'
import {
  setUserInfo,
  setToken,
  getToken,
  getUserInfo,
  removeAll
} from '@/store/Store'

const system = {
  state: {
    token: getToken(),
    userInfo: getUserInfo()
  },
  mutations: {
    SET_TOKEN: (state, token) => {
      state.token = token
      if (token) setToken(token)
    },
    SET_USERIFNO: (state, userInfo) => {
      state.userInfo = userInfo
      if (userInfo) setUserInfo(userInfo)
    }
  },
  actions: {
    changeUser ({ commit }, token) {
      commit('SET_TOKEN', undefined)
      commit('SET_USERIFNO', undefined)
      commit('SET_TOKEN', token)
      userInfo().then(ret => {
        commit('SET_USERIFNO', ret || {})
      })
      uni.reLaunch({
        url: '/pages/index/home'
      })
    },
    login ({ commit }, params) {
      login(params.params, params.config).then(ret => {
        commit('SET_TOKEN', ret.access_token)
        userInfo().then(ret => {
          // 微信·环境
          commit('SET_USERIFNO', ret || {})
        })
      })
    },
    logout ({ commit }) {
      logout().then(ret => {
        commit('SET_TOKEN', undefined)
        commit('SET_USERIFNO', undefined)
        removeAll()
        uni.reLaunch({
          url: '/pages/index/login'
        })
      })
    }
  }
}
export default system
